package com.h2.common.util.email.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

/**
 * A utility class for emails.
 *
 * @since 2.1
 */
public final class SmtpUtils {
   
   public static final String SMTP_HOST_PROPERTY = "mail.smtp.host";
   
   public static final String EMAIL_REGEX =
      "^[\\w\\.-]+@([\\w\\-]+\\.)+[a-zA-Z]{2,4}$";
   
   protected static final Pattern PATTERN = Pattern.compile(EMAIL_REGEX);
   
   ////
   ////

   private SmtpUtils() {
   }
   
   /**
    * Converts the input to a collection of InternetAddress.
    *
    * @param input
    * @return
    * @throws AddressException
    * @since 2.1
    */
   public static Collection<InternetAddress> toInternetAddress(
         Collection<String> input) throws AddressException {
      if (input == null || input.isEmpty()) {
         return Collections.emptyList();
      }
      Collection<InternetAddress> addresses = new ArrayList<InternetAddress>(
            input.size());
      for (String address : input) {
         addresses.add(new InternetAddress(address));
      }
      return addresses;
   }
   
   /**
    * Converts the input to an array of InternetAddress.
    *
    * @param input
    * @return
    * @throws AddressException
    * @since 2.1
    */
   public static InternetAddress[] toInternetAddressArray(String... input)
         throws AddressException {
      if (input == null || input.length < 1) {
         return new InternetAddress[0];
      }
      InternetAddress[] addresses = new InternetAddress[input.length];
      for (int i = 0; i < input.length; i++) {
         addresses[i] = new InternetAddress(input[i]);
      }
      return addresses;
   }

   public static boolean isAddressValid(String address) {
      boolean isValid = false;
      
      Matcher matcher = PATTERN.matcher(address);
      if (matcher.matches()) {
         isValid = true;
      }
      return isValid;
   }
}
